import React, {Component, PropTypes} from 'react';
import {Row, Col, Tree, Input, Button, Radio, Icon} from 'antd';
import {getImage, getStatusImage} from "../../services/showServer";
import {Scrollbars} from 'react-custom-scrollbars';
import classNames from 'classnames';

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const TreeNode = Tree.TreeNode;
const InputGroup = Input.Group;

function strSub(str) {
  if (str != null) {
    if (str.length > 40) {
      return str.substring(0, 40) + "...";
    } else {
      return str;
    }
  }
}

class BindSelectContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      expandedKeys: [],
      searchValue: '',
      selectedKeys: [],
      treeData: {
        "servers": [],
      }
    };
  }

  componentDidMount() {
  }

  onRadioChange(e) {
    getStatusImage(e.target.value).then(function (json) {
      this.setState({
        expandedKeys: [],
        searchValue: '',
        selectedKeys: [],
        focus: false,
        treeData: json
      });
    }.bind(this));
  }

  onCheck(info) {
    this.setState({
      selectedKeys: info
    });
  }

  componentDidMount() {
    getStatusImage(11101).then(function (json) {
      if (json.servers) {
        this.setState({
          treeData: json
        });
      }
    }.bind(this));
  }

  bindClick() {
    // 获取选择节点，过滤根节点（服务节点）
    var servers = this.state.treeData.servers;
    var slist = [];
    for (var i in servers) {
      slist.push(servers[i].id);
    }

    var selects = this.state.selectedKeys;
    var selectList = [];
    for (var i in selects) {
      var id = selects[i];
      var isServer = false;
      for (var j in slist) {
        if (id == slist[j]) {
          isServer = true;
        }
      }
      if (!isServer) {
        selectList.push(id);
      }
    }
    // console.log(selectList);
    this.props.signal.dispatch(selectList);

  }

  onExpand = (expandedKeys) => {
    this.setState({expandedKeys});
  }

  handleInputChange(e) {
    const value = e.target.value;
    console.log(value)
    const expandedKeys = [];
    this.state.treeData.servers.forEach((item) => {
      const serverId = item.id;
      item.dbs.forEach((dbitem) => {
        const dbId = dbitem.id;
        if (dbitem.name.indexOf(value) > -1) {
          expandedKeys.push(serverId);
        }
        dbitem.tables.forEach((taitem) => {
          if (taitem.name.indexOf(value) > -1) {
            expandedKeys.push(dbId);
          }
        });
      });
    });
    this.setState({
      expandedKeys: expandedKeys,
      searchValue: value,
    });
  }

  handleFocusBlur(e) {
    this.setState({
      focus: e.target === document.activeElement,
    });
  }

  handleSearch() {
    const value = this.state.searchValue;
    const expandedKeys = [];
    this.state.treeData.servers.forEach((item) => {
      const serverId = item.id;
      item.dbs.forEach((dbitem) => {
        const dbId = dbitem.id;
        if (dbitem.name.indexOf(value) > -1) {
          expandedKeys.push(serverId);
        }
        dbitem.tables.forEach((taitem) => {
          if (taitem.name.indexOf(value) > -1) {
            expandedKeys.push(dbId);
          }
        });
      });
    });
    this.setState({
      expandedKeys: expandedKeys,
    });
  }

  render() {
    const {searchValue, expandedKeys} = this.state;

    const ServerLoop = data => data.map((item) => {
      if (item.dbs) {
        return <TreeNode title={<span><Icon type="home"/>&nbsp;&nbsp;&nbsp;{strSub(item.name)}</span>}
                         key={item.id}>{DBLoop(item.dbs)}</TreeNode>;
      }
      return <TreeNode title={<span><Icon type="home"/>&nbsp;&nbsp;&nbsp;{strSub(item.name)}</span>}
                       key={item.id}></TreeNode>;
    });

    const DBLoop = data => data.map((item) => {
      var index = item.name.search(searchValue);
      var beforeStr = item.name.substr(0, index);
      var afterStr = item.name.substr(index + searchValue.length);
      const title = index > -1 ? (
        <span>
          {beforeStr}
          <span style={{color: '#FF5500'}}>{searchValue}</span>
          {afterStr}
        </span>
      ) : <span>{item.name}</span>;

      if (item.tables) {
        return <TreeNode title={<span><Icon type="hdd"/>&nbsp;&nbsp;&nbsp;{title}</span>}
                         key={item.id}>{TableLoop(item.tables)}</TreeNode>;
      }
      return <TreeNode title={<span><Icon type="hdd"/>&nbsp;&nbsp;&nbsp;{title}</span>}
                       key={item.id}></TreeNode>;
    });

    const TableLoop = data => data.map((item) => {
      var index = item.name.search(searchValue);
      var beforeStr = item.name.substr(0, index);
      var afterStr = item.name.substr(index + searchValue.length);
      const title = index > -1 ? (
        <span>
          {beforeStr}
          <span style={{color: '#FF5500'}}>{searchValue}</span>
          {afterStr}
        </span>
      ) : <span>{item.name}</span>;
      return <TreeNode title={<span><Icon type="file-text"/>&nbsp;&nbsp;&nbsp;{title}</span>}
                       key={item.id}></TreeNode>;
    });

    const treeNodes = ServerLoop(this.state.treeData.servers);

    const btnCls = classNames({
      'ant-search-btn': true,
      'ant-search-btn-noempty': !!this.state.searchValue.trim(),
    });
    const searchCls = classNames({
      'ant-search-input': true,
      'ant-search-input-focus': this.state.focus,
    });

    return (
      <div>
        <Row>
          <Col span={4}>
            <Button type="ghost" icon="left" onClick={this.bindClick.bind(this)}>绑定数据</Button>
            <br/>
            <br/>
          </Col>
          <Col span={4}>
          </Col>
          <Col span={16}>
            <RadioGroup onChange={this.onRadioChange.bind(this)} defaultValue="11101">
              <RadioButton value="11101">全库数据</RadioButton>
              <RadioButton value="01000">新增数据</RadioButton>
            </RadioGroup>
            <br/>
            <br/>
          </Col>
        </Row>
        <Row>
          <Col span={24}>
            <InputGroup className={searchCls} style={{ width: 380 }}>
              <Input placeholder="" value={searchValue} onChange={this.handleInputChange.bind(this)}
                     onFocus={this.handleFocusBlur.bind(this)} onBlur={this.handleFocusBlur.bind(this)} onPressEnter={this.handleSearch.bind(this)}
              />
              <div className="ant-input-group-wrap">
                <Button icon="search" className={btnCls} size="default" onClick={this.handleSearch.bind(this)}/>
              </div>
            </InputGroup>
          </Col>
        </Row>
        <br/>
        <Row>
          <Col span={24}>
            <Scrollbars style={{width: 380, height: 660}}
                        autoHide={true}
                        autoHideTimeout={1000}
                        autoHideDuration={200}
                        thumbMinSize={30}
                        universal={true}>
              <Tree className="image" showLine checkable
                    onCheck={this.onCheck.bind(this)}
                    onExpand={this.onExpand.bind(this)}
                    expandedKeys={expandedKeys}
              >
                {treeNodes}
              </Tree>
            </Scrollbars>
          </Col>
        </Row>
      </div>
    );
  }
}

export default BindSelectContainer;
